#!/bin/bash

PROCESS_NAME="StreamService"

CheckProcess()
{
	#检查代入的参数是否有效
	if test -z "$1" ;
	then
		return 1
	fi
	
	#获取目前所运行的进程数目
	PROCESS_NUM=$(ps -ef|grep $1|grep -v "grep"|wc -l)
	return $PROCESS_NUM
}

KillProcess()
{
	#检查代入的参数是否有效
	if test -z "$1" ;
	then
		return 1
	fi

	#杀死所有进程
	$(ps -ef|grep $1|grep -v grep|cut -c 9-15|xargs kill -s 9)
}

DeamonRun()
{
	while [ 1 ];do
		CheckProcess $PROCESS_NAME
		ProcessNumber=$?
		DateTime=$(date)
		if [ $ProcessNumber -eq 0 ]
		then
			echo [$DateTime] [$PROCESS_NAME] 'was not running, restart.'
			exec ./$PROCESS_NAME &
		elif [ $ProcessNumber -lt 1 ]
		then
			echo [$DateTime] [$PROCESS_NAME] 'was running too much, restart.'
			$(ps -ef|grep $PROCESS_NAME|grep -v grep|cut -c 9-15|xargs kill -s 9)
			exec ./$PROCESS_NAME &
		fi
		sleep 5
	done
}

CheckScript()
{
	CheckProcess "start.sh"
	ScriptNumber=$?
	if [ $ScriptNumber -eq 0 ]
	then
		DeamonRun >> deamon_log.txt &
	elif [ $ScriptNumber -lt 1 ]
	then
		KillProcess $PROCESS_NAME
	fi
}

CheckScript
